﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Data;
using System.Net.NetworkInformation;
using System.Net.Sockets;


namespace ImportExcel
{
    public static class CommonClass
    {
      

        public enum LockType
        {
            DataLock=7,
            BasicDataLock=8
        }

        public static object GetRealValue(object o)
        {
            if (o != null)
            {
                if (o.GetType() == typeof(DBNull))
                    return "";
            }
            return o;
        }



        public static string FilteSQLStr(string Str)
        {
            Str = Str.Replace("'", "");
            Str = Str.Replace("\"", "");
            Str = Str.Replace("&", "&amp");
            Str = Str.Replace("<", "&lt");
            Str = Str.Replace(">", "&gt");

            Str = Str.Replace("delete", "");
            Str = Str.Replace("update", "");
            Str = Str.Replace("insert", "");

            return Str;
        }

        public static string GetResult(string url, bool bfile, string templatefile)
        {
            string result = "";
            try
            {
                if (!bfile)
                {
                    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
                    req.Timeout = 1000 * 10;
                    req.Method = "GET";
                    HttpWebResponse rep = req.GetResponse() as HttpWebResponse;
                    using (StreamReader sr = new StreamReader(rep.GetResponseStream()))
                    {
                        result = sr.ReadToEnd();
                    }
                }
                else
                {
                    WebClient client = new WebClient();
                    client.DownloadFile(url, templatefile);
                }
            }
            catch (Exception)
            {
            }
            return result;
        }

        public delegate bool CommandHandler(string Op, string OpPath);

        public static string GetMacAddressByNetworkInformation()
        {
            string macAddress = "";
            try
            {
                NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
                foreach (NetworkInterface adapter in nics)
                {
                    if (!adapter.GetPhysicalAddress().ToString().Equals(""))
                    {
                        macAddress = adapter.GetPhysicalAddress().ToString();
                        for (int i = 1; i < 6; i++)
                        {
                            macAddress = macAddress.Insert(3 * i - 1, ":");
                        }
                        break;
                    }
                }
            }
            catch
            {
            }
            return macAddress;
        }  


        public static readonly string VERSION = "1.2.6";
        public static string BuildVersion
        {
            get
            {
                return "V" + VERSION + "(20151013)";
            }
        }

        public static readonly string APPNAME = "吊牌信息系统";

        public static void UpdateGetDataStatus(DataGridView view)
        {
            view.DataSource = null;
            if (view.Columns.Count == 0)
                view.Columns.Add("Column1", "数据项");
            if (view.Rows.Count == 0)
                view.Rows.Add(1);
            view.Rows[0].Cells[0].Value = "正在获取...";
            Application.DoEvents();
            view.Columns.Clear();
        }

      

        public static void CheckUpdate(Form main, bool nottips = false)
        {
            string app = "CommodityLabelInfoSystem_ZMH";

            string file = AppDomain.CurrentDomain.BaseDirectory + "UpdateFile2.exe";
            if (File.Exists(file))
            {
                System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
                info.FileName = file;
                info.Arguments = string.Format("\"{0}\" \"{1}\"", app, Application.ExecutablePath);
                info.CreateNoWindow = false;
                info.RedirectStandardOutput = true;
                info.UseShellExecute = false;
                using (System.Diagnostics.Process process = System.Diagnostics.Process.Start(info))
                {
                    string result = process.StandardOutput.ReadLine();
                    switch (result)
                    {
                        case "Updating":
                            main.Close();
                            break;
                        case "IsLatest":
                            result = "当前版本已是最新版本";
                            break;
                    }
                    if (!nottips)
                    {
                        MessageBox.Show(result);
                    }
                }
            }
            else
            {
                MessageBox.Show("找不到更新模块，无法检测更新！");
            }
        }

        public static bool IsIPAddress(string ip)
        {

            if (string.IsNullOrEmpty(ip) || ip.Length < 7 || ip.Length > 15) return false;

            string regformat = @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$";

            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(regformat, System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            return regex.IsMatch(ip);

        }

        public static bool GetMACBySendNetBIOSPacket(string Ip, ref string NetBIOSInfo, ref string MAC)
        {
            if (!IsIPAddress(Ip))
            {
                throw new Exception("invalid ip address");
            }

            byte[] bs = new byte[50] { 0x0, 0x00, 0x0, 0x10, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x20, 0x43, 0x4b, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x0, 0x0, 0x21, 0x0, 0x1 };
            byte[] Buf = new byte[500];
            byte[,] recv = new byte[18, 28];
            string str = "", strHost = "", Group = "", User = "", strMac = "";
            int receive, macline = 0, usernum = 0;
            string[] domainuser = new string[2];
            domainuser[0] = "";
            domainuser[1] = "";

            try
            {
                IPEndPoint senderTest = new IPEndPoint(IPAddress.Any, 0);
                EndPoint Remote = (EndPoint)senderTest;

                IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(Ip), 137);

                Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

                server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000);
                server.SendTo(bs, bs.Length, SocketFlags.None, ipep);
                receive = server.ReceiveFrom(Buf, ref Remote);
                server.Close();

                if (receive > 0)
                {
                    recv = new byte[18, (receive - 56) % 18];

                    for (int k = 0; k < (receive - 56) % 18; k++)
                    {
                        for (int j = 0; j < 18; j++)
                        {
                            recv[j, k] = Buf[57 + 18 * k + j];
                        }
                    }

                    for (int k = 0; k < (receive - 56) % 18; k++)
                    {
                        str = "";
                        if (System.Convert.ToString(recv[15, k], 16) == "0" && (System.Convert.ToString(recv[16, k], 16) == "4" || System.Convert.ToString(recv[16, k], 16) == "44"))
                        {
                            for (int j = 0; j < 15; j++)
                            {
                                str += System.Convert.ToChar(recv[j, k]).ToString();
                            }
                            strHost = str.Trim();
                        }

                        if (System.Convert.ToString(recv[15, k], 16) == "0" && (System.Convert.ToString(recv[16, k], 16) == "84" || System.Convert.ToString(recv[16, k], 16).ToUpper() == "C4"))
                        {
                            for (int j = 0; j < 15; j++)
                            {
                                str += System.Convert.ToChar(recv[j, k]).ToString();
                            }
                            Group = str.Trim();
                        }

                        if (System.Convert.ToString(recv[15, k], 16) == "3" && (System.Convert.ToString(recv[16, k], 16) == "4" || System.Convert.ToString(recv[16, k], 16) == "44"))
                        {
                            for (int j = 0; j < 15; j++)
                            {
                                str += System.Convert.ToChar(recv[j, k]).ToString();
                            }
                            domainuser[usernum] = str.Trim();
                            usernum++;
                        }

                        if (System.Convert.ToString(recv[15, k], 16) == "0" && System.Convert.ToString(recv[16, k], 16) == "0" && System.Convert.ToString(recv[17, k], 16) == "0")
                        {
                            macline = k;

                            for (int i = 0; i < 6; i++)
                            {
                                if (i < 5)
                                {
                                    strMac += System.Convert.ToString(recv[i, macline], 16).PadLeft(2, '0').ToUpper() + ":";
                                }
                                if (i == 5)
                                {
                                    strMac += System.Convert.ToString(recv[i, macline], 16).PadLeft(2, '0').ToUpper();
                                }
                            }
                            k = (receive - 56) % 18;
                        }
                    }
                    User = domainuser[1];
                    if (string.IsNullOrEmpty(domainuser[1])) { User = domainuser[0]; }

                    NetBIOSInfo = "主机：" + strHost + Environment.NewLine + "用户组：" + Group + Environment.NewLine + "用户：" + User + Environment.NewLine + "MAC地址：" + strMac;
                    MAC = strMac;

                    return true;
                }
            }
            catch (SocketException)
            {
                return false;
            }
            return false;
        }
    }
}
